package com.panshi.api.config;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Ajax工具类
 *
 * @author  weiminke
 * @version 2020年5月6日
 */
public class AjaxUtils {
	
	/**
	 * 响应json数据
	 * @param obj
	 * @throws IOException
	 */
	public static void respJsonWrite(Object obj,HttpServletResponse response){
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json;charset=UTF-8");//application/json在Openfeign支持类型,其他类型会出现错误,出发默认更改类型
		PrintWriter printWriter;
		try {
			printWriter = response.getWriter();
			printWriter.print(JSONObject.toJSONString(obj));
		} catch (IOException e) {
			throw new RuntimeException("响应写入Json字符IO异常", e);
		}
		
	}
	
	/**
	 * 是否是Ajax请求
	 * @param req
	 */
	public static boolean isAjaxReq(HttpServletRequest req){
		if("XMLHttpRequest".equalsIgnoreCase(req.getHeader("X-Requested-With"))) {
			return true;
		}else {
			String contentType=req.getHeader("Content-Type");
			if("application/json".equals(contentType)) {
				return true;
			}
		}
		return false;
	}
	
}
